<template>
  <div class="cate">
    <div class="cate-search flex items-center">
      <img src="@/assets/images/search.png" />
      <el-input
        class="cate-search-input"
        v-model="keyword"
        placeholder="输入搜索内容"
      />
      <el-button
        style="height: 42px"
        class="h-full"
        type="primary"
        round
        @click="listUpdate"
      >
        搜索
      </el-button>
    </div>

    <div class="cate-content flex">
      <ul class="filter">
        <li
          style="margin-bottom: 10px"
          v-for="item in filterList"
        >
          <div
            style="margin-bottom: 8px"
            v-if="item.label"
          >
            {{ item.label }}
          </div>
          <template v-if="item.type === 'date-picker'">
            <el-date-picker
              style="width: 100%; box-sizing: border-box"
              v-model="item.value"
              type="yearrange"
              range-separator="~"
              start-placeholder="请选择开始时间"
              end-placeholder="请选择结束时间"
              value-format="YYYY"
              @change="filterChg()"
            />
          </template>
          <template v-else>
            <el-select
              v-model="item.value"
              :placeholder="`请选择${item.label}`"
              @change="filterChg()"
            >
              <el-option
                v-for="option in item.options"
                :key="option.code"
                :label="option.name"
                :value="option.code"
              />
            </el-select>
          </template>
        </li>
        <li>
          <el-tree
            :data="treeData"
            :load="treeLoadNode"
            lazy
            highlight-current
            :expand-on-click-node="false"
            :props="{ label: 'label', isLeaf: 'isLeaf' }"
            @node-click="treeChg"
          />
        </li>
      </ul>
      <section
        class="flex-1 bg-white"
        v-loading="loading"
      >
        <template v-if="list?.length">
          <ol class="list">
            <li
              class="list-item flex"
              v-for="item in list"
              @click="onListItem(item)"
            >
              <book-cover
                :cover="item?.cover"
                :empty="item?.coverEmpty"
                :title="item?.title"
              />
              <div class="list-item-content">
                <!-- title -->

                <p class="font-bold mb-10">
                  [{{ item?.docName }}]&nbsp;&nbsp;
                  <template v-if="hlResult && hlResult[item?.recordId]?.title">
                    <span v-html="hlResult[item?.recordId].title"></span>
                  </template>
                  <template v-else>
                    {{ item?.title }}
                  </template>
                </p>
                <!-- <p class="mb-10">{{ item.callNoOne }}</p> -->
                <p
                  class="mb-10"
                  v-html="hlResult && hlResult[item?.recordId]?.callNo"
                ></p>

                <p class="mb-10">{{ item?.author }}</p>
                <p class="mb-10">
                  {{ item?.publisher }}；{{ item?.publishYear }}；{{
                    item?.isbns.join("；")
                  }}
                </p>
                <p>{{ item?.adstract }}</p>
              </div>
            </li>
          </ol>

          <div
            class="flex justify-center items-center"
            style="height: 80px"
          >
            <el-pagination
              v-model:current-page="page"
              v-model:page-size="rows"
              :page-sizes="[10, 20, 3, 40, 50]"
              layout="prev, pager, next, total, sizes, jumper"
              :total="total"
              @change="paginationChg"
              background
            />
          </div>
        </template>
        <template v-else>
          <el-empty :description="loading ? '数据加载中' : '暂无数据'" />
        </template>
      </section>
    </div>
  </div>
</template>

<script setup>
import { find } from "@/api/modules/find";
import { getCovers } from "@/utils/cover/cover";
import { getDicItem } from "@/utils/dict/index";
import BookCover from "@/components/book-cover/book-cover.vue";
const { detailInfoUpdate } = inject("detail-store");
const Route = useRoute();
const Router = useRouter();
const keyword = ref();
const loading = ref(false);
const hlResult = ref({});
const page = ref(1);
const rows = ref(10);
const total = ref(0);
const list = ref([]);
const searchFieldContent = ref("*");
const filterList = ref([
  {
    label: "资料类型",
    apiKey: "documentTypeList",
    sendKey: "docCode",
    value: "all",
  },
  {
    label: "资源类型",
    sendKey: "resourceType",
    dicKey: "resourceType",
    value: "all",
  },
  {
    label: "国别",
    sendKey: "countryCode",
    apiKey: "countryList",
    value: "all",
  },
  { label: "语种", sendKey: "langCode", apiKey: "languageList", value: "all" },
  {
    label: "校区",
    sendKey: "campusId",
    dicKey: "campusCode",
    value: "all",
    keys: { name: "campusName", code: "campusId" },
  },
  {
    label: "馆藏地",
    sendKey: "locationId",
    dicKey: "locationId",
    value: "all",
  },
  {
    label: "出版/发行日期",
    sendKey: ["publishBegin", "publishEnd"],
    value: [],
    type: "date-picker",
  },
]);
const treeData = ref();
const treeLoadNode = (node, resolve, reject) => {
  const { data, level } = node;
  // console.log("node", node);
  // console.log("data", data);
  // if ("flag" in data && data?.flag) {
  // }
  let parmas = {
    classCode: data?.classCode || "1",
    classLev: level + 1,
    parentClassNo: data?.classNo || "",
  };
  find.category.classifica.list(parmas).then(({ data }) => {
    let list = data.map((item) => {
      return {
        ...item,
        label: `${item.classNo} ${item.className}`,
        isLeaf: !item.flag,
        children: [],
      };
    });
    // console.log(list);
    resolve(list);
  });
};
const treeChg = (data) => {
  searchFieldContent.value = data.classNo;
  listUpdate();
};
const filterChg = () => {
  listUpdate();
};
const paginationChg = (currentPage, pageSize) => {
  page.value = currentPage;
  rows.value = pageSize;
  listUpdate();
};
const onListItem = (listItem) => {
  detailInfoUpdate({
    recordId: listItem.recordId,
    coverEmpty: listItem.coverEmpty,
    cover: listItem.cover,
  });
  Router.push({
    path: "/detail",
  });
};
onMounted(() => {
  keyword.value = Route.query.keyword;
  filterListInit();
  listUpdate();
});

function listUpdate() {
  loading.value = true;
  let params = {
    searchFieldContent: "*",
    searchField: "callNo",
    sortField: "relevance",
    sortClause: "desc",
    page: 1,
    rows: 10,
    categorySearchFlag: 1,
    docCode: [],
    resourceType: [],
    subject: [],
    discode1: [],
    publisher: [],
    locationId: [],
    collectionName: [],
    author: [],
    langCode: [],
    countryCode: [],
    coreInclude: [],
    ddType: [],
    verifyStatus: [],
    group: [],
    onlyOnShelf: null,
    campusId: [],
    publishBegin: null,
    publishEnd: null,
  };
  const filterParams = filterList.value.reduce(
    (init, item) => {
      if (Array.isArray(item.sendKey)) {
        // console.log("item.value", item.value);
        item.sendKey.forEach((key, index) => {
          init[key] = (item.value && item.value[index]) || "";
        });
      } else {
        init[item.sendKey] = item.value === "all" ? [] : [item.value];
      }
      return init;
    },
    {
      searchFieldContent: searchFieldContent.value,
      page: page.value,
      rows: rows.value,
      searchField: keyword.value ? "keyWord" : "callNo",
      searchFieldContent: keyword.value || "*",
    }
  );
  let sendParams = Object.assign(params, filterParams);
  // console.log("sendParams", sendParams);

  find.unify
    .search(sendParams)
    .then(({ data }) => {
      hlResult.value = data.hlResult;
      total.value = data.numFound;
      getCovers(data.searchResult).then((resList) => {
        list.value = resList;
        console.log("resList", list.value);
        loading.value = false;
      });
    })
    .catch(() => {
      loading.value = false;
    });
  // params = Object.assign(params);
}

async function filterListInit() {
  const getConditionList = await find.category
    .getConditionList()
    .then(({ data }) => data);
  // console.log("getConditionList", getConditionList);
  filterList.value.forEach((item, index) => {
    if (item.dicKey || item.apiKey) {
      let initArr = [{ name: "全部", code: "all" }];
      if (item.dicKey) {
        let listNew = keysFormat(getDicItem(item.dicKey), item.keys);
        item.options = initArr.concat(listNew);
      } else if (item.apiKey) {
        let listNew = getConditionList[item.apiKey];
        item.options = initArr.concat(keysFormat(listNew, item.keys));
      }
    }
    // else if (item.apiFn) {
    //   item.apiFn(index);
    // }
  });
  console.log("filterList.value", filterList.value);
}

function keysFormat(list, keys) {
  return list.map((cItem) => {
    const codeKey = keys?.code || "code";
    const nameKey = keys?.name || "name";
    return {
      ...cItem,
      code: cItem[codeKey],
      name: cItem[nameKey],
    };
  });
}
</script>

<style lang="scss" scoped>
.cate {
  &-search {
    width: 100%;
    max-width: 1200px;
    height: 56px;
    margin: 0 auto;
    background: #ffffff;
    box-shadow: inset 0px 3px 6px 1px rgba(0, 0, 0, 0.16);
    border-radius: 999px;
    padding: 12px;
    box-sizing: border-box;
    & > img {
      --siz: 26px;
      width: var(--siz);
      height: var(--siz);
    }
    &-input {
      font-size: 28px;
      //   --el-input-border-color: unset !important;
      //   --el-border-color: unset;
      :deep(.el-input__wrapper) {
        box-shadow: unset;
      }
    }
  }
  &-content {
    margin-top: 20px;
    border-radius: 8px;

    .filter {
      width: 320px;
      background: #fff;
      margin-right: 20px;
      padding: 16px;
      box-sizing: border-box;
    }
    .list {
      &-item {
        padding: 16px;
        border-bottom: 1px solid #ebebeb;
        box-sizing: border-box;
        &:hover {
          box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.16);
        }
        &-content {
          margin-left: 20px;
        }
      }
    }
  }
}
</style>
